import React, { Component } from 'react';
import LayoutContentWrapper from '@iso/components/utility/layoutWrapper';
import LayoutContent from '@iso/components/utility/layoutContent';
import axios from "../../../../http";
import Card from "../../../UIElements/Card/Card.styles";
import Button from '@iso/components/uielements/button';

import Modals from '@iso/components/Feedback/Modal';

import ModalStyle, { ModalContent } from '../../../Feedback/Modal/Modal.styles';
import WithDirection from '@iso/lib/helpers/rtl';

import {Fieldset, Form, Label} from "../../../FirestoreCRUD/Article/Article.styles";
import Input, { Textarea } from '@iso/components/uielements/input';
import Qs from 'qs'
import message from '@iso/components/Feedback/Message';
import MessageContent from "../../../Feedback/Message/Message.styles";
import {
    DateCell,
    ImageCell,
    LinkCell,
    TextCell,
} from '@iso/components/Tables/HelperCells';

import TableWrapper from "../../../Tables/AntTables/AntTables.styles";
import {Col, Row, Space, Tree} from "antd";
import PopconfirmWrapper from "../../../Feedback/Popconfirm/Popconfirm.styles";
import Popconfirms from '@iso/components/Feedback/Popconfirm';
import {InputGroup} from "../../../../components/uielements/input";
import PageHeader from '@iso/components/utility/pageHeader';
const isoModal = ModalStyle(Modals);
const Modal = WithDirection(isoModal);



const Popconfirm = (props) => (
    <PopconfirmWrapper>
        <Popconfirms {...props} />
    </PopconfirmWrapper>
);



export default class extends React.Component {


    constructor(props) {
        super(props);
        this.state={dataList:[],modalVisible:false,modalEditVisible:false,q_genName:''};
    }


     renderCell = (object, type, key) => {
        const value = object[key];
        switch (type) {
            case 'ImageCell':
                return ImageCell(value);
            case 'DateCell':
                return DateCell(value);
            case 'LinkCell':
                return LinkCell(value);
            default:
                return TextCell(value);
        }
    };

    showAddModal(){
        this.setState({modalVisible:true,genName:'',genValue:'',memo:''})
    };

    handleCancel = () => {
        this.setState({modalVisible:false})
    };

    showEditModal(item){
        let state={modalEditVisible:true, id:item.id, genName:item.genName,genValue:item.genValue,memo:item.memo};
        this.setState(state)
    };

    handleEditCancel = () => {
        this.setState({modalEditVisible:false})
    };

    onRecordChange = (event, key) => {
        let state={};
        state[key]=event.target.value;
        this.setState(state)
    };
    loadData(page){
        axios.post('api/core/configuration/idgenerator/findByPage', Qs.stringify({
            page: page-1,
            size: 10,
            genName:this.state.q_genName
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{

                let  data=response.data

                let  dataList=data.data.content;

                let totalElements=data.data.totalElements;

                this.setState({dataList:dataList,totalElements:totalElements});
            })
            .catch(function (error) {
                console.log(error);
            });

    }



    add=() =>{
        let entity={genName:this.state.genName,genValue:this.state.genValue,memo:this.state.memo};
        axios.post('api/core/configuration/idgenerator/add', Qs.stringify({
            requestJson:JSON.stringify(entity)
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{
                let  data=response.data;
                if(data.status==1){
                    this.setState({modalVisible:false})
                    this.loadData(1);
                    this.showSuccessMessage(data.message)
                }else{
                    this.showErrorMessage(data.message);
                }

            })
            .catch(function (error) {
                console.log(error);
            });

    }
    update=() =>{
        let entity={id:this.state.id,genName:this.state.genName,genValue:this.state.genValue,memo:this.state.memo};
        axios.post('api/core/configuration/idgenerator/update', Qs.stringify({
            requestJson:JSON.stringify(entity)
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{
                let  data=response.data;
                if(data.status==1){
                    this.setState({modalEditVisible:false})
                    this.loadData(1);
                    this.showSuccessMessage(data.message)
                }else{
                    this.showErrorMessage(data.message);
                }

            })
            .catch(function (error) {
                console.log(error);
            });

    }


    deleteById(id) {

        axios.post('api/core/configuration/idgenerator/deleteById', Qs.stringify({
            id:id
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{
                let  data=response.data;
                if(data.status==1){
                    this.loadData(1);
                    this.showSuccessMessage(data.message)
                }else{
                    this.showErrorMessage(data.message);
                }

            })
            .catch(function (error) {
                console.log(error);
            });

    }


   componentDidMount() {


        this.loadData(1)
   }

   showSuccessMessage (systemMessage){
        message.success(
            <MessageContent>
                {systemMessage}
            </MessageContent>,
            5
        );
    };
    showErrorMessage (systemMessage){
        message.error(
            <MessageContent>
                {systemMessage}
            </MessageContent>,
            5
        );
    };


    getColumns(){
        const columns = [ {
            title: 'ID',
            key: 'id',
            width: 100,
            render: object => this.renderCell(object, 'TextCell', 'id'),
        },{
            title: '主键名称',
            key: 'genName',
            width: 100,
            render: object => this.renderCell(object, 'TextCell', 'genName'),
        },{
            title: '下一个值',
            key: 'genValue',
            width: 100,
            render: object => this.renderCell(object, 'TextCell', 'genValue'),
        },{
            title: '备注',
            key: 'memo',
            width: 100,
            render: object => this.renderCell(object, 'TextCell', 'memo'),
        },{
            title: '创建时间',
            key: 'createTime',
            width: 100,
            render: object => this.renderCell(object, 'TextCell', 'createTime'),
        },{
            title: '操作',
            width: 100,
            render:(text,record) => (
            <Space size="middle">
                <Button
                    key="submit"
                    type="primary"
                    size="small"
                    onClick={()=>this.showEditModal(record)}
                >
                    编辑
                </Button>


                <Popconfirm
                    title="确定要执行删除操作吗？"
                    okText="是"
                    cancelText="否"
                    onConfirm={()=>this.deleteById(record.id)}

                >
                    <Button
                        key="submit"
                        type="danger"
                        size="small"

                    >
                        删除
                    </Button>
                </Popconfirm>
            </Space>
            )
        }];

        const sortColumns = [
            { ...columns[0], sorter: false },
            { ...columns[1], sorter: false },
            { ...columns[2], sorter: false },
            { ...columns[3], sorter: false },
            { ...columns[4], sorter: false },
            { ...columns[5], sorter: false },
            { ...columns[6], sorter: false }
        ];
        return sortColumns;
    }

    getPagination(){
      let pagination= {
        showSizeChanger: false,//设置每页显示数据条数
        showQuickJumper: false,
        showTotal: () => `共${this.state.totalElements}条`,
        pageSize: 10,
          //数据的总的条数
        total: this.state.totalElements,
          //点击当前页码
        onChange: (current) => this.loadData(current),
          //设置每页显示数据条数，current表示当前页码，pageSize表示每页展示数据条数
        onShowSizeChange: (current, pageSize) => {
            console.log(pageSize);
            //this.onShowSizeChange(current, pageSize)
        }

     }
     return pagination;
    }


    render() {
    return (
      <LayoutContentWrapper style={{ height: '100vh' }}>
          <PageHeader>
              主键管理
          </PageHeader>
        <LayoutContent>
            <Modal
                visible={this.state.modalVisible}
                title="添加"
                onCancel={this.handleCancel}
                footer={[
                    <Button key="back" size="small" onClick={this.handleCancel}>
                        取消
                    </Button>,
                    <Button
                        key="submit"
                        type="primary"
                        size="small"
                        onClick={this.add}
                    >
                        确定
                    </Button>,
                ]}
            >
                <Form>
                        <Fieldset>
                            <Label>*主键名称:</Label>
                            <Input
                                label="名称"
                                placeholder="请输入主键名称"
                                value={this.state.genName}
                                onChange={e => this.onRecordChange(e, 'genName')}
                            />
                        </Fieldset>
                        <Fieldset>
                            <Label>*下一个值:</Label>
                            <Input
                                label="下一个值"
                                placeholder="请输入下一个值"
                                value={this.state.genValue}
                                onChange={e => this.onRecordChange(e, 'genValue')}
                            />
                        </Fieldset>
                        <Fieldset>
                            <Label>备注:</Label>
                            <Input
                                label="备注"
                                placeholder="请输入备注"
                                value={this.state.memo}
                                onChange={e => this.onRecordChange(e, 'memo')}
                            />
                        </Fieldset>



                    </Form>

            </Modal>


            <Modal
                visible={this.state.modalEditVisible}
                title="编辑"
                onCancel={this.handleEditCancel}
                footer={[
                    <Button key="back" size="small" onClick={this.handleEditCancel}>
                        取消
                    </Button>,
                    <Button
                        key="submit"
                        type="primary"
                        size="small"
                        onClick={this.update}
                    >
                        确定
                    </Button>,
                ]}
            >
                <Form >
                    <Fieldset>
                        <Label>*主键名称:</Label>
                        <Input
                            label="名称"
                            placeholder="请输入主键名称"
                            value={this.state.genName}
                            onChange={e => this.onRecordChange(e, 'genName')}
                        />
                    </Fieldset>
                    <Fieldset>
                        <Label>*下一个值:</Label>
                        <Input
                            label="下一个值"
                            placeholder="请输入下一个值"
                            value={this.state.genValue}
                            onChange={e => this.onRecordChange(e, 'genValue')}
                        />
                    </Fieldset>
                    <Fieldset>
                        <Label>备注:</Label>
                        <Input
                            label="备注"
                            placeholder="请输入备注"
                            value={this.state.memo}
                            onChange={e => this.onRecordChange(e, 'memo')}
                        />
                    </Fieldset>

                </Form>

            </Modal>

            <Card
                title='查询条件'
                style={{ width: '100%' }}
            >

                <InputGroup size="large" style={{ marginBottom: '15px' }}>
                    <Row gutter={8}>
                        <Col span={3}>
                            <Input placeholder='主键名称' onChange={e => this.onRecordChange(e, 'q_genName')} />
                        </Col>


                        <Col span={3}>
                            <Button type="primary" size='small' onClick={()=>{this.loadData(1)}}>
                                查询
                            </Button>
                        </Col>
                    </Row>
                </InputGroup>


            </Card>
            <Button type="primary" size='small' onClick={()=>{this.showAddModal()}}>
                添加
            </Button>
            <Card
                title='主键管理'
                style={{ width: '100%' }}
            >

                <TableWrapper
                    columns={this.getColumns()}
                    dataSource={this.state.dataList}
                    className="isoSortingTable"
                    pagination={this.getPagination()}
                />

            </Card>



        </LayoutContent>
      </LayoutContentWrapper>
    );
  }
}
